<?php
// 获取温度数据API
// 返回数据库中的温度数据用于图表展示

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');
header('Access-Control-Allow-Headers: Content-Type');

// 引入数据库配置
require_once 'config.php';

// 只处理GET请求
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    echo json_encode(['status' => 'error', 'message' => '只允许GET请求']);
    exit;
}

try {
    // 获取数据库连接
    $pdo = getDBConnection();
    
    // 查询最近30条温度数据，按时间戳排序
    $stmt = $pdo->prepare("SELECT id, timestamp, temperature, devid, devmac, token, param1, param2, param3, param4, param5, created_at FROM temperature_data ORDER BY timestamp DESC LIMIT 30");
    $stmt->execute();
    $data = $stmt->fetchAll();
    
    // 格式化数据用于图表展示
    $chartData = [];
    foreach ($data as $row) {
        $chartData[] = [
            'timestamp' => $row['timestamp'],
            'datetime' => date('Y-m-d H:i:s', $row['timestamp']),
            'temperature' => (float)$row['temperature'],
            'devid' => $row['devid'],
            'devmac' => $row['devmac'],
            'token' => $row['token'],
            'param1' => $row['param1'],
            'param2' => $row['param2'],
            'param3' => $row['param3'],
            'param4' => $row['param4'],
            'param5' => $row['param5']
        ];
    }
    
    // 按时间戳升序排列（从旧到新）
    usort($chartData, function($a, $b) {
        return $a['timestamp'] <=> $b['timestamp'];
    });
    
    // 返回成功响应
    echo json_encode([
        'status' => 'success',
        'message' => '数据获取成功',
        'data' => $chartData
    ]);
    
} catch (Exception $e) {
    // 错误处理
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => '数据库操作失败: ' . $e->getMessage()]);
}
?>